import '../../public.dart';

class AddBankCardPage extends StatefulWidget {
  const AddBankCardPage({super.key});

  @override
  State<AddBankCardPage> createState() => _AddBankCardPageState();
}

class _AddBankCardPageState extends State<AddBankCardPage> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  int? selectedBankCardTypeId;
  String? selectedBankName;
  String? bankCardNumber;
  String? accountName;
  bool isLoading = false;
  List<SysBankCardTypeEntity> bankCardTypes = [];
  List<SysBankCardTypeEntity> filteredBankCardTypes = [];
  String searchQuery = '';

  @override
  void initState() {
    super.initState();
    _loadBankCardTypes();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _loadBankCardTypes() async {
    try {
      final response = await BankCardApi.getList();
      if (response.content != null) {
        setState(() {
          bankCardTypes = response.content!;
          filteredBankCardTypes = response.content!;
        });
      }
    } catch (error) {
      if (mounted) {
        BrnToast.show('Failed to load bank card types', context);
      }
    }
  }

  String? validateBankCardType(int? value) {
    if (value == null) {
      return 'Please select a bank card type';
    }
    return null;
  }

  String? validateBankCardNumber(String? value) {
    if (value == null || value.isEmpty) {
      return 'Please enter bank card number';
    }
    // 移除所有空格和特殊字符，只保留数字和字母
    final cleanedNumber = value.replaceAll(RegExp(r'\s+'), '');
    if (cleanedNumber.length < 8 || cleanedNumber.length > 20) {
      return 'Bank card number must be between 8 and 20 characters';
    }
    return null;
  }

  String? validateAccountName(String? value) {
    if (value == null || value.isEmpty) {
      return 'Please enter account name';
    }
    if (value.length < 2 || value.length > 50) {
      return 'Account name length must be between 2 and 50 characters';
    }
    return null;
  }

  Future<void> _addBankCard() async {
    final form = formKey.currentState;
    if (form!.validate()) {
      form.save();

      setState(() {
        isLoading = true;
      });

      try {
        // 移除银行卡号中的空格
        final cleanedCardNumber = bankCardNumber!.replaceAll(
          RegExp(r'\s+'),
          '',
        );

        final clientUserBankDto = ClientUserBankDto(
          bankCardTypeId: selectedBankCardTypeId!,
          bankCard: cleanedCardNumber,
          accountName: accountName!,
        );

        await BankCardApi.bindToUser(clientUserBankDto);

        if (mounted) {
          BrnToast.show('Bank card added successfully', context);
          // 返回上一页
          RouterHelper.navigator.pop(true);
        }
      } catch (error) {
        if (mounted) {
          BrnToast.show('Failed to add bank card', context);
        }
      } finally {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () {
            RouterHelper.navigator.pop();
          },
        ),
        title: const Text(
          'Add Bank Card',
          style: TextStyle(color: Colors.black, fontSize: 18),
        ),
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.only(bottom: 20),
        children: [
          _header(),
          Form(
            key: formKey,
            child: Column(
              children: [
                _bankCardTypeSelector(),
                _bankCardNumberInput(),
                _accountNameInput(),
                const SizedBox(height: 40),
                _submitButton(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _header() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Add a new bank card',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 10),
          Text(
            'Please enter your bank card details below',
            style: TextStyle(color: Colors.grey[600], fontSize: 14),
          ),
        ],
      ),
    );
  }



  Widget _bankCardTypeSelector() {
    return buildFormItem(
      InkWell(
        onTap: _showBankCardTypeDialog,
        child: InputDecorator(
          decoration: getCommonInputDecoration(
            hintText: 'Select bank card type',
            labelText: 'Bank Card Type',
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                selectedBankName ?? 'Select a bank card type',
                style: TextStyle(
                  color: selectedBankName != null ? Colors.black : Colors.grey,
                ),
              ),
              const Icon(Icons.arrow_drop_down, color: Colors.grey),
            ],
          ),
        ),
      ),
    );
  }

  void _showBankCardTypeDialog() {
    List<SysBankCardTypeEntity> dialogFilteredBankTypes = bankCardTypes;

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16.0),
          topRight: Radius.circular(16.0),
        ),
      ),
      backgroundColor: Colors.white,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            void filterBankTypes(String query) {
              if (query.isEmpty) {
                dialogFilteredBankTypes = bankCardTypes;
              } else {
                dialogFilteredBankTypes = bankCardTypes
                    .where((bank) =>
                        bank.typeName != null &&
                        bank.typeName!
                            .toLowerCase()
                            .contains(query.toLowerCase()))
                    .toList();
              }
              setState(() {});
            }

            return Container(
              padding: const EdgeInsets.all(16.0),
              constraints: BoxConstraints(
                minWidth: MediaQuery.of(context).size.width,
                maxHeight: MediaQuery.of(context).size.height * 0.7,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 添加一个指示器
                  Container(
                    width: 40,
                    height: 4,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2),
                      color: Colors.grey.shade300,
                    ),
                    margin: const EdgeInsets.only(bottom: 16.0),
                  ),
                  const Text(
                    'Select a bank',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  // 搜索框
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.0),
                      border: Border.all(
                        color: Colors.grey.shade300,
                        width: 1.0,
                      ),
                    ),
                    child: Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(left: 12),
                          child: Icon(Icons.search, color: Colors.grey),
                        ),
                        Expanded(
                          child: TextField(
                            onChanged: filterBankTypes,
                            decoration: const InputDecoration(
                              hintText: 'Search for bank',
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.symmetric(
                                vertical: 12,
                                horizontal: 12,
                              ),
                            ),
                            autofocus: true,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 添加滚动视图以支持大量选项
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.only(bottom: 16.0),
                      physics: const BouncingScrollPhysics(),
                      child: Column(
                        children: [
                          // 银行列表
                          if (dialogFilteredBankTypes.isEmpty)
                            const Padding(
                              padding: EdgeInsets.all(24.0),
                              child: Text(
                                'No banks available',
                                textAlign: TextAlign.center,
                                style: TextStyle(color: Colors.grey),
                              ),
                            )
                          else
                            ...dialogFilteredBankTypes.map(
                              (bank) => _buildBankOption(context, bank),
                            ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildBankOption(BuildContext context, SysBankCardTypeEntity bank) {
    bool isSelected = selectedBankCardTypeId == bank.id;

    return InkWell(
      onTap: () {
        _selectBankCardType(bank);
        Navigator.pop(context);
      },
      splashColor: Colors.grey.shade200,
      highlightColor: Colors.grey.shade100,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 16),
        decoration: BoxDecoration(
          border: const Border(
            bottom: BorderSide(color: Color(0xFFEEEEEE), width: 0.5),
          ),
          color: isSelected ? Colors.grey.shade50 : Colors.transparent,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Text(
                bank.typeName ?? '',
                style: TextStyle(
                  fontSize: 15,
                  color: isSelected ? const Color(0xFF4CAF50) : Colors.black87,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            // 如果选中，显示勾选图标
            if (isSelected)
              const Icon(
                Icons.check_circle,
                color: Color(0xFF4CAF50),
                size: 20,
              ),
          ],
        ),
      ),
    );
  }

  void _selectBankCardType(SysBankCardTypeEntity bank) {
    setState(() {
      selectedBankCardTypeId = bank.id;
      selectedBankName = bank.typeName;
    });
  }

  Widget _bankCardNumberInput() {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validateBankCardNumber,
        onSaved: (value) => bankCardNumber = value,
        onChanged: (value) => bankCardNumber = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: 'Enter bank card number',
          labelText: 'Bank Card Number',
        ),
      ),
    );
  }

  Widget _accountNameInput() {
    return buildFormItem(
      TextFormField(
        keyboardAppearance: Brightness.light,
        keyboardType: TextInputType.text,
        validator: validateAccountName,
        onSaved: (value) => accountName = value,
        onChanged: (value) => accountName = value,
        cursorWidth: 1.5,
        cursorColor: const Color.fromRGBO(51, 51, 51, 1),
        decoration: getCommonInputDecoration(
          hintText: 'Enter account name',
          labelText: 'Account Name',
        ),
      ),
    );
  }

  Widget _submitButton() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ElevatedButton(
        onPressed: isLoading ? null : _addBankCard,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.black,
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 20),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        ),
        child: isLoading
            ? const CircularProgressIndicator(color: Colors.white)
            : const Text(
                'Add Bank Card',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
      ),
    );
  }
}
